import re
import datetime

from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from users.models import VerifyCode
from settings import REGEX_MOBILE

User = get_user_model()


class UserRegSerializer(serializers.ModelSerializer):
    """
    用户信息序列化,这里有一点要注意，就是code这个字段，是前端给我们post的，但是这个code并不是我们User的字段
    """
    code = serializers.CharField(max_length=4, min_length=4, required=True, help_text='验证码', label='验证码',
                                 error_messages={
                                     "required": '请输入验证码',  # required针对的是没有post这个字段名，
                                 }, write_only=True)
    username = serializers.CharField(required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=User.objects.all(), message="用户已存在")],
                                     label="用户名")
    password = serializers.CharField(style={'input_type': 'password'}, write_only=True)

    def validated_code(self, code):
        # self.initial_data 保存的是前端传过来的所有值，
        verify_codes = VerifyCode.objects.filter(code=self.code, mobile=self.initial_data.get('username')).order_by(
            'add_time')
        if verify_codes:
            last_code = verify_codes[0]
            pre_time = datetime.datetime.now() - datetime.timedelta(hours=0, minutes=100, seconds=0)
            if pre_time > last_code.add_time:
                raise serializers.ValidationError('验证码已过有效期')
            if last_code.code != code:
                raise serializers.ValidationError('验证码错误')
        else:
            raise serializers.ValidationError('请填写验证码')

    def validate(self, attrs):
        """
        attrs表示返回的总的数据的dict
        """
        attrs['mobile'] = attrs['username']
        del attrs['code']
        return attrs

    #     因为这个model中不保存code，所以里可以不return

    # def create(self, validated_data):
    #     user = super(UserRegSerializer, self).create(validated_data=validated_data)
    #     user.set_password(validated_data['password'])
    #     user.save()
    #     return user

    class Meta:
        model = User
        fields = ('code', 'username', 'password')


class SmsSerializer(serializers.Serializer):
    """
    注意这里不是用的ModelSerializer,这是因为在VerifyCode中code中必填字段，但是这里还没有生成code
    """
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):
        """
        验证手机号码
        """
        # 验证手机是否已注册,这里应该判断用户行为是否是注册，如果不是注册则不用此验证
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError('用户已存在')
        # 验证手机号是否合法
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError('手机号非法')
        # 验证频率
        pre_time = datetime.datetime.now() - datetime.timedelta(hours=0, minutes=100, seconds=0)
        if VerifyCode.objects.filter(add_time__gt=pre_time, mobile=mobile):
            raise serializers.ValidationError('距离上一次发送未超过50秒')

        return mobile
